package com.starblink.product.detail.postrecommend

import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.UserRelationCodeEnum
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.util.post.PostUtils
import com.starblink.android.common.utils.PostDetailHelp
import com.starblink.android.common.view.decoration.SpaceItemDecoration
import com.starblink.android.common.view.expand.ExpandableTextView
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.autosize.utils.AutoSizeUtils
import com.starblink.basic.ext.contentViewHeight2
import com.starblink.basic.style.view.round.CornerType
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.ScreenUtils
import com.starblink.comment.ui.CommentPostListDialog
import com.starblink.comment.ui.PostCommentDialog
import com.starblink.product.R
import com.starblink.product.databinding.ItemMountProductBinding
import com.starblink.product.databinding.ItemRecommendVideoDetail2Binding
import com.starblink.product.view.MountedProductHolder
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.Poster
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.starblink.videocache.cache.PreloadManager


class VideoDetailHolder(
    binding: ItemRecommendVideoDetail2Binding,
    private val mActivity: AppCompatActivity,
    val isRecommend: Boolean = false,//是否是一屏一卡视频
    val spmPageValue: Int = 0,//
    val pageTrackTag: String = "",//
    val isFromFeeds: Boolean = false,
    val list: ArrayList<Any>? = null,
    val guideCall: ((binding: ItemRecommendVideoDetail2Binding) -> Unit)? = null,
    val onMutedClick: ((id: String, isMute: Boolean) -> Unit)? = null, //静音
    val onSearchPicClick: () -> Unit, //识图
    val shareCallBack: (id: String) -> Unit,
    val showMountedDialog: (() -> Unit)? = null,
    val dismissMountedDialog: (() -> Unit)? = null,
) :
    BaseBindingVH<PostD, ItemRecommendVideoDetail2Binding>(binding = binding) {

    private var isMute = true//视频静音
    var hasShowed: Boolean = false//是否已初始化过
    var hasNext = true//有下一个
    lateinit var post: PostD

    override fun onBind(post: PostD, position: Int) {
        this.post = post
        itemView.tag = post

        if (position == 0) {
            if (!hasShowed) {
                Log.e("ProductDetailCardView", "==1===$position==${post.id}")
                itemView.trackData(
                    page = spmPageValue,
                    element = SpmElementDef.DetailContent,
                    traceInfo = post.traceInfo,
                    params = SpmTrackHandler.trackPostMap(
                        position,
                        post
                    ),
                    showRatio = 0.9f,
//                businessSuffixID = businessSuffixId("PostD", post.id)
                    businessSuffixID = businessSuffixId(post)
                )
                hasShowed = true
            }
        } else {
            Log.e("ProductDetailCardView", "==1===$position==${post.id}")
            itemView.trackData(
                page = spmPageValue,
                element = SpmElementDef.DetailContent,
                traceInfo = post.traceInfo,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post
                ),
                showRatio = 0.9f,
//                businessSuffixID = businessSuffixId("PostD", post.id)
                businessSuffixID = businessSuffixId(post)
            )
        }

        hasNext = position < (list?.size ?: 0) - 1
        initLayoutParams(position)
        binding.includeBottom.tvName.text = "@ ${post.posterInfo.poster.username}"

        binding.includeRight.tvComment.text =
            if (post.commentCount == 0) "" else post.commentCount.toString()
        binding.includeRight.tvShare.text =
            if (post.shareCount == 0) "" else post.shareCount.toString()

        setFollowState(post.posterInfo.poster.relationCode, binding.includeRight.tvFollow)
        if (post.liked) {
            binding.includeRight.ivLike.setImageResource(com.starblink.android.common.R.mipmap.video_like)
        } else {
            binding.includeRight.ivLike.setImageResource(com.starblink.android.common.R.mipmap.video_unlike)
        }
        binding.includeRight.tvLike.text =
            if (post.likeNumbers == 0) "" else post.likeNumbers.toString()

        PostDetailHelp.showPostUser(
            mActivity,
            post.posterInfo,
            binding.includeRight.ivUser,
            binding.includeBottom.tvName,
            deleteColor = com.starblink.basic.style.R.color.sk_gray200,
            nameColor = com.starblink.basic.style.R.color.white,
            needAt = true
        )
//        PostDetailHelp.showTopicView(
//            mActivity,
//            post.operatorHashtagList,
//            binding.includeBottom.flTopic
//        )

        if (post.content != null) {
            binding.includeBottom.tvTitle.visibility = View.VISIBLE
            val accountHashtagList: List<PostD.AccountHashtagList?> =
                post.accountHashtagList ?: listOf()

            val tvContent: ExpandableTextView = binding.includeBottom.tvTitle as ExpandableTextView
            val viewWidth: Int = ScreenUtils.getScreenWidth(mActivity) - AutoSizeUtils.dp2px(
                mActivity,
                90f
            )
            tvContent.initWidth(viewWidth)
            tvContent.maxLines = 4
            tvContent.setHasAnimation(true)
            tvContent.setCloseInNewLine(false)
            tvContent.setOpenSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray0_opacity50))
            tvContent.setCloseSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray0_opacity50))
            val topicChar =
                tvContent.replaceTopicSpan(
                    accountHashtagList,
                    post.content,
                    com.starblink.basic.style.R.color.sk_gray50
                ) { ///跳转去hashtag详情
                        name, id ->
//                    mActivity.navigationTo(RoutePage.Post.PAGE_HASHTAG) {
//                        withString(RoutePage.Post.TOPIC_ID, id)
//                    }
                }
            tvContent.setOriginalText(
                topicChar
            )
        } else {
            binding.includeBottom.tvTitle.visibility = View.GONE
        }
//        onBindVideo(position, post)

        val pictures = post.pictures
        //开始预加载
        if (pictures != null && pictures.isNotEmpty()) {
            val picUrl = pictures[0].pictureF.picUrl
            PreloadManager.getInstance(mActivity).addPreloadTask(picUrl, position)
            binding.tiktokView.setImageUrl(mActivity, post.mainPic)
        }
        showMountedProduct(
            binding.includeBottom.rightDivide,
            binding.includeBottom.llProduct,
            binding.includeBottom.recycler,
            post
        )
        guideCall?.invoke(binding)
        setListener(post, position)
    }

    private fun initLayoutParams(position: Int) {
        binding.divide.visibleOrGone(false) {}
        if (isRecommend) {
            var containerH = mActivity.contentViewHeight2
//            var containerH = screenHeight

            if (position < 3 && hasNext) {
                containerH -= dp2px(62f)//存在引导
                binding.divide.visibleOrGone(true) {}

                binding.llContainer.updateLayoutParams {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    height = containerH
                }
            } else {
                binding.llContainer.updateLayoutParams {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                }
            }
            binding.container.setCornerRadius(
                CommUtils.dip2px(32f),
                CornerType.TOP_LEFT,
            )
            binding.container.setCornerRadius(
                CommUtils.dip2px(32f),
                CornerType.TOP_RIGHT,
            )

            binding.includeBottom.ivOpenVoice.visibleOrGone(true) {}
            binding.llBottom.setBackgroundResource(R.drawable.pro_video_bottom_bg)
            binding.includeBottom.ivOpenVoice.setOnClickListener {
//                gsyVideoPlayer.startAfterPrepared()
                isMute = !isMute
                onMutedClick?.invoke(post.id, isMute)
                if (!isMute) {
                    binding.includeBottom.ivOpenVoice.setImageResource(com.starblink.android.common.R.mipmap.icon_video_open_voice)
                } else {
                    binding.includeBottom.ivOpenVoice.setImageResource(com.starblink.android.common.R.mipmap.icon_video_no_voice)
                }
            }
        } else {
            binding.llBottom.setBackgroundResource(R.drawable.video_bottom_bg)
            binding.tvBottomComment.visibleOrGone(true) {}
            binding.tvBottomComment.setOnClickListener {//直接评论
                LoginCheckInterceptor.check2Login(mActivity) {
                    val inputTextMsgDialog =
                        PostCommentDialog(
                            mActivity,
                            com.starblink.android.basic.R.style.dialog_center
                        )
                    inputTextMsgDialog.setTextSendListener {
                        addComment(post, binding.includeRight.tvComment)
                    }
                    inputTextMsgDialog.setId(post.id)
                    inputTextMsgDialog.setContentType(post.contentType ?: "1")
                    inputTextMsgDialog.show()
                }
            }
        }
    }

//    val gsyVideoPlayer: SampleCoverVideo = binding.videoPlayer
//
//    private fun onBindVideo(
//        position: Int,
//        post: VideoPost,
//    ) {
////        val gsyVideoManager = gsyVideoPlayer.gsyVideoManager
//        val pictures = post.pictures
//        var url = ""
//        if (pictures != null && pictures.isNotEmpty()) {
//            url = pictures.first().pictureF?.picUrl ?: ""
//        }
//        if (url.isNotEmpty() && !hasPlayed) {
//            hasPlayed = true
//            gsyVideoOptionBuilder = GSYVideoOptionBuilder()
//            //防止错位，离开释放
//            //gsyVideoPlayer.initUIState();
//            GSYVideoManager.instance().isNeedMute = isNeedMute
//            gsyVideoOptionBuilder!!
//                .setIsTouchWiget(false) //.setThumbImageView(imageView)
//                .setUrl(url)
//                .setCacheWithPlay(true)
//                .setLooping(true)
//                .setThumbPlay(false)
//                .setRotateViewAuto(false)
//                .setLockLand(true)
//                .setPlayTag("RecommendVideo_${post.id}")
//                .setShowFullAnimation(false)
//                .setNeedLockFull(false)
//                .setPlayPosition(position)
////                .setStartAfterPrepared(false)
//                .setShowPauseCover(true)
//                .setVideoAllCallBack(object : GSYSampleCallBack() {
//                    override fun onStartPrepared(url: String?, vararg objects: Any?) {
//                        super.onStartPrepared(url, *objects)
//                        GSYVideoManager.instance().isNeedMute = isNeedMute
//                    }
//
//                    override fun onPrepared(url: String, vararg objects: Any) {
//                        super.onPrepared(url, *objects)
//                        //静音
//                        GSYVideoManager.instance().isNeedMute = isNeedMute
//                    }
//
//                    override fun onClickStartThumb(url: String?, vararg objects: Any?) {
//                        super.onClickStartThumb(url, *objects)
//                    }
//
//                    override fun onClickBlank(url: String?, vararg objects: Any?) {
//                        super.onClickBlank(url, *objects)
//                        pauseVideo()
//                    }
//                }).build(gsyVideoPlayer)
//            gsyVideoPlayer.loadCoverImage(
//                post.mainPic,
//                com.starblink.basic.style.R.mipmap.default_white
//            )
//            gsyVideoPlayer.setOnClickListener {//跳转详情
//                pauseVideo()
//            }
//            binding.ivStart.setOnClickListener {//暂停视频
//                pauseVideo()
//            }
////            gsyVideoPlayer.onVideoPause()
////            gsyVideoPlayer.startPlayLogic()
//
//        }
//    }
//
//    private fun pauseVideo() {
//        if (gsyVideoPlayer.gsyVideoManager.isPlaying) {
//            isPause = true
////            gsyVideoPlayer.onVideoPause()
//            gsyVideoPlayer.gsyVideoManager.pause()
//            binding.ivStart.visibleOrGone(true) {}
//        } else {
//            isPause = false
//            gsyVideoPlayer.gsyVideoManager.start()
//            binding.ivStart.visibleOrGone(false) {}
//        }
//    }

    private fun showMountedProduct(
        right: View, llProduct: FrameLayout, recycler: RecyclerView, post: PostD,
    ) {
        var productList: ArrayList<ProductF> = arrayListOf()//挂载商品

        post.productList?.let {
            llProduct.visibleOrGone(it.isNotEmpty()) {
                ///获取挂载商品
                if (post.productList != null && post.productList!!.isNotEmpty()) {
                    for (i in post.productList?.indices!!) {
                        val item = post.productList!![i]
                        if (i < 5) {
                            productList.add(item.productF)
                        }
                    }
                }
                right.visibleOrGone(productList.size > 1) {}

                val mAdapter: MutableAdapter by lazyOnNone {
                    MutableAdapter(productList).apply {
                        addVhDelegate {
                            MountedProductHolder(
                                ItemMountProductBinding.inflate(it.inflater, it, false),
                                mActivity,
                                needLeftPadding = false,
                                showDialog = showMountedDialog,
                                dismissDialog = dismissMountedDialog
                            )
                        }
                    }
                }
                recycler.layoutManager =
                    LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

                if (recycler.itemDecorationCount === 0) {
                    recycler.addItemDecoration(
                        SpaceItemDecoration.newHorizontalDecoration(CommUtils.dip2px(5))
                    )
                }
                recycler.adapter = mAdapter

                recycler.isHorizontalSlideToBottom(isBottom = {
                    right.setBackgroundResource(com.starblink.android.common.R.drawable.right_video_bottom_radiu_bg)
                }, isNotBottom = {
                    right.setBackgroundResource(com.starblink.android.common.R.drawable.right_video_bottom_bg)
                })
            }
        }
    }

    //设置点击事件
    private fun setListener(
        post: PostD, position: Int,
    ) {
        binding.includeRight.ivLike.run {
            trackData(
                page = SpmPageDef.VideoDetailRoute,
                element = SpmElementDef.videoDetailLike,
                onlyHit = true,
                traceInfo = post.traceInfo,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post
                ).plus(
                    "result" to if (post.liked) "0" else "1"
                )
            )
            click {//点赞
                CommonMutateManage.likePost(
                    mActivity,
                    post.id,
                    post.contentType,
                    post.posterInfo.poster.id,
                    post.liked,
                    post.likeNumbers,
                    {
                        changeLikeState(
                            !post.liked,
                            if (!post.liked) post.likeNumbers + 1 else post.likeNumbers - 1,
                            binding.includeRight.ivLike, binding.includeRight.tvLike,
                        )
                    }) { like, count ->
                    ApolloValSetExt.setApolloVal<PostD>(post, "liked", like)
                    ApolloValSetExt.setApolloVal<PostD>(post, "likeNumbers", count)
                    this.trackData(
                        page = SpmPageDef.VideoDetailRoute,
                        element = SpmElementDef.videoDetailLike,
                        onlyHit = true,
                        traceInfo = post.traceInfo,
                        params = SpmTrackHandler.trackPostMap(
                            position,
                            post
                        ).plus(
                            "result" to if (post.liked) "0" else "1"
                        )
                    )
                    changeLikeState(
                        like, count,
                        binding.includeRight.ivLike, binding.includeRight.tvLike,
                    )
                }
            }
        }
        binding.includeRight.tvFollow.setOnClickListener {//关注
            CommonMutateManage.followUser(
                mActivity,
                post.posterInfo.poster.id,
                post.posterInfo.poster.relationCode,
                {
                    setFollowState(
                        if (!PostUtils.followed(post.posterInfo.poster.relationCode)) UserRelationCodeEnum.FOLLOW.ordinal else UserRelationCodeEnum.NOTHING.ordinal,
                        binding.includeRight.tvFollow
                    )
                }) { state ->

                ApolloValSetExt.setApolloVal<Poster>(post.posterInfo.poster, "relationCode", state)
                setFollowState(state, binding.includeRight.tvFollow)
            }
        }
        binding.includeRight.ivShare.setOnClickListener {//分享
            var productStr = PostDetailHelp.getShareProductListString(post.productList)
            ShareDialog(
                this.mActivity,
                if (!isRecommend) "${ShareUrlUtils().getUrl(ShareTypeEnum.VIDEO_POST)}${post.id}" else
                    "${ShareUrlUtils().getUrl(ShareTypeEnum.VIDEO_POST)}${post.id}&type=1&productList=$productStr&countryCode=${UserDataCenter.getLocalCountryCode()}",
                shareCome = ShareTypeEnum.VIDEO_POST, imageUrl = post.mainPic
            ) {
                shareCallBack.invoke(post.id)
            }.show(this.mActivity.supportFragmentManager, "share")

            AppsflyerManager.reportContentShare(
                mapOf(
                    "af_content_id" to post.id,
                    "af_content_type" to (post.contentType ?: "1"),
                )
            )
        }

        binding.includeRight.ivComment.click {//评论
            CommentPostListDialog(
                mActivity,
                post.id, post.contentType ?: "1", post.commentCount
            ) {
                addComment(post, binding.includeRight.tvComment)
            }.show(mActivity.supportFragmentManager, "comment")
        }

        binding.includeRight.ivSearch.run {
            trackData(
                page = SpmPageDef.VideoDetailRoute,
                element = SpmElementDef.VideoProductWidget,
                onlyHit = true,
                traceInfo = post.traceInfo,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post
                )
            )
            click {//识图
                onSearchPicClick.invoke()
            }
        }
    }

    private fun addComment(
        post: PostD,
        tvComment: TextView,
    ) {
        ApolloValSetExt.setApolloVal<PostD>(post, "commentCount", post.commentCount + 1)
        tvComment.text = post.commentCount.toString()
    }


    private fun setFollowState(relationCode: Int, tvFollow: ImageView) {
        if (PostUtils.followed(relationCode)) {
            tvFollow.setImageResource(com.starblink.basic.style.R.mipmap.icon_user_followed)
        } else {
            tvFollow.setImageResource(com.starblink.basic.style.R.mipmap.icon_user_follow)
        }
    }

    private fun changeLikeState(
        liked: Boolean = false,
        likeNum: Int, ivLike: ImageView, tvLike: TextView,
    ) {
        if (liked) {
            ivLike.setImageResource(com.starblink.android.common.R.mipmap.video_like)
        } else {
            ivLike.setImageResource(
                com.starblink.android.common.R.mipmap.video_unlike
            )
        }
        tvLike.text = "$likeNum"
    }
}